package cloudLibrary;

import java.io.IOException;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/*
 * this class registers a user in the Users table of the database. 
 */

@SuppressWarnings("serial")
public class ItemCreatorServlet extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user == null)
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI())); // demand
																				// user
																				// to
																				// be
																				// logged
																				// in.
		String title = "";
		String type = "";

		try {
			title = req.getParameter("title");
			type = req.getParameter("type");

		} catch (Exception e) {
			resp.sendRedirect("?page=newItem&error=fields");
		}

		if ((title == null || type == null) || title.equals("")) {
			resp.sendRedirect("?page=newItem&error=fields");
		} else {
			PersistenceManager pm = PMF.get().getPersistenceManager();
		    String query = "select from " + Item.class.getName() + " where title=='"+ title +"' && type=='" + type + "' && owner=='" + user.getEmail() + "'";
		    List<Item> items = (List<Item>) pm.newQuery(query).execute();
		    if (items.isEmpty()) {
				Item u = new Item(user.getEmail(), title, type);
				try {
					pm.makePersistent(u);
					resp.sendRedirect("?msg=itemsaved");
	
				} finally {
					pm.close();
				}
		    }
		    else {
		    	resp.sendRedirect("?page=newItem&error=alreadyin");
		    }
		    }
		}

	public boolean isRegisted(String email) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Users.class);
		query.setFilter("email == emailParam");
		query.declareParameters("String emailParam");

		try {
			List<Users> results = (List<Users>) query.execute(email);
			if (!results.isEmpty()) {
				return true;
			} else {
				return false;
			}
		} finally {
			query.closeAll();
		}

	}

}
